﻿var $table = $('#table');
$(function () {
    initTable();

    $('.btn-primary.btn.btn-sm').click(function (e) {

        var tar = $(e.target).text();

        for (var i = 0; i < $('button[name="btn-search"]').length; i++) {

            var item = $('button[name="btn-search"]')[i];
            if (tar == $.trim($(item).text())) {
                switch (i) {
                    case 0:
                        var l7 = $('#last7').val();
                        $('#beginDate').val(l7.split(':')[0]);
                        $('#endDate').val(l7.split(':')[1]);
                        break;
                    case 1:
                        var lm = $('#lastMonth').val();
                        $('#beginDate').val(lm.split(':')[0]);
                        $('#endDate').val(lm.split(':')[1]);
                        break;
                    case 2:
                        var tm = $('#thisMonth').val();
                        $('#beginDate').val(tm.split(':')[0]);
                        $('#endDate').val(tm.split(':')[1]);
                        break;
                }
            }
        }
        refreshTable();

    });
});
var orderBy = "";
var table_queryParams = function (params) {
    var data = {};
    if (parent.CustomerSource_Index_data != undefined) {
        data = parent.CustomerSource_Index_data;
    } else {
        data = $("#mainForm").formToJson(false);
    }
    parent.CustomerSource_Index_data = undefined;
    data.pageIndex = (params.offset / params.limit) + 1;
    //data.pageSize = params.limit;
    //data.orderBy = this.sortName;
    //data.orderByType = this.sortOrder;

    console.log(data);
    return data;
};

function initTable() {
    $table.bootstrapTable({
        url: '/BusinessLoan/IndexAsync',            //数据来源地址
        method: 'post',                     //数据请求方式
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否启用分页
        sidePagination: 'server',           //在服务器端分页
        queryParams: queryParams,           //传递参数
        pageNumber: 1,                      //初始化加载第一页，默认第一页
        pageSize: 20,                       //每页的记录行数（*）
        pageList: [10, 20, 30, 40, 50],     //可供选择的每页的行数（*）
        clickToSelect: true,                //是否启用点击选中行
        //search: true,
        //strictSearch: true,
        //searchOnEnterKey: true,

        showRefresh: true,
        showColumns: true,
        toolbar: '#trr',
        iconSize: 'outline',
        icons: {
            refresh: 'glyphicon-repeat',
            columns: 'glyphicon-list'
        },
        //toolbar: "#tableToolBar",
        height: getHeight(),
        columns: [{
            //    width: 38,
            //    field: 'selected',
            //    checkbox: true,
            //}, {
            title: '行号',
            align: 'center',
            formatter: function (value, row, index) { return index + 1; }
        }, {
            //    field: 'Name',
            //    title: '名称',
            //    align: 'center',
            //}, {
            field: 'state',//正常 超时 终止
            title: '状态',
            align: 'center',
            formatter: function (value, row, index) {
                var _arr = [];
                if (value == 0) {
                    _arr = ['<span class="glyphicon glyphicon-stop" aria-hidden="true" style="color:red;"></span>']
                } else if (value == 1) {
                    //return "正常";
                    _arr = ['<span class="glyphicon glyphicon-play" aria-hidden="true" style="color:green;"></span>']
                } else if (value == 2) {
                    //return "异常";
                    _arr = ['<span class="glyphicon glyphicon-pause" aria-hidden="true" style="color:red;"></span>']
                } else if (value == 3) {
                    //return "完成";//glyphicon glyphicon-stop
                    _arr = ['<span class="glyphicon glyphicon-stop" aria-hidden="true" style="color:green;"></span>']
                }
                return _arr.join("", _arr);
            }
        }, {
            field: 'intermediaryName',
            title: '门店',
            align: 'center',
        }, {
            field: 'userName',
            title: '联系人',
            align: 'center',
        }, {
            field: 'userPhone',
            title: '联系人电话',
            align: 'center',
            visible: false,
        }, {
            field: 'customerName',
            title: '客户',
            align: 'center',
            events: {
                'click .glyphicon-edit':
                    function (e, value, row, index) {
                        openEditRunning('修改客户信息', 9, row.id, index);
                        //parent.layer.open({
                        //    type: 2,
                        //    title: '修改客户信息',
                        //    shadeClose: false,
                        //    shade: 0.4,
                        //    area: ['400px', '300px'],
                        //    content: '/Finance/Running/Edit?id=' + row.id + '&type=9',
                        //    end: function () {
                        //        refreshTable();
                        //    }
                        //});
                    }
            },
            formatter: function (value, row, index) {
                var _arr = [value];
                if (isAuthority('295')) {
                    _arr.push('<i class="glyphicon glyphicon-edit pull-right" aria-hidden="true" title="修改"></i>');
                }
                return _arr.join(" ", _arr);
            }
        }, {
            field: 'customerPhone',
            title: '客户电话',
            align: 'center',
            events: {
                'click .glyphicon-edit': function (e, value, row, index) {
                    openEditRunning('修改客户信息', 10, row.id, index);
                }
            },
            formatter: function (value, row, index) {
                var _arr = [value];
                if (isAuthority('296')) {
                    _arr.push('<i class="glyphicon glyphicon-edit pull-right" aria-hidden="true" title="修改"></i>');
                }
                return _arr.join(" ", _arr);
            }
        }, {
            field: 'transferDetailed',
            title: '转件',
            align: 'center',
            events: {
                'click .glyphicon-edit': function (e, value, row, index) {
                    openEditRunning('转件明细', 2, row.id, index);
                    //parent.layer.open({
                    //    type: 2,
                    //    title: '转件明细',
                    //    shadeClose: false,
                    //    shade: 0.4,
                    //    area: ['400px', '300px'],
                    //    content: '/Finance/Running/Edit?id=' + row.id + '&type=2',
                    //    end: function () {
                    //        refreshTable();
                    //        //window.location.reload();
                    //    }
                    //});
                }
            },
            formatter: function (value, row, index) {
                var _arr = ['<span class="glyphicon glyphicon-star" aria-hidden="true" style="color:' + (value == 0 ? "red" : "green") + ';"></span>'
                , '<i class="glyphicon glyphicon-edit pull-right" aria-hidden="true" title="修改"></i>']
                return _arr.join("", _arr);
            }
        }, {
            field: 'buildingName',
            title: '小区名称',
            align: 'center',
        }, {
            field: 'address',
            title: '详细地址',
            align: 'center',
            visible: false,
        }, {
            field: 'price',
            title: '成交价格',
            align: 'center',
            visible: false,
        }, {
            field: 'area',
            title: '面积',
            align: 'center',
            visible: false,
        }, {
            field: 'houseOwnerName',
            title: '房主',
            align: 'center',
        }, {
            field: 'houseOwnerPhone',
            title: '房主电话',
            align: 'center',
        }, {
            field: 'filingTime',
            title: '报备时间',
            align: 'center',
        }, {
            title: '进度',
            align: 'center',
            formatter: function (value, row, index) {
                var arr = [];
                if (row.filingState == 1) {
                    arr.push("报备");
                    arr.push("进行中");
                    //arr.push(row.filingTime);
                } else if (row.filingState == 2) {
                    //console.log(row.progressState);

                    arr.push(row.progressState);
                    //arr.push(row.progressTime);
                }
                else if (row.filingState == 3) {//3审核未通过
                    arr.push("报备 被拒绝");
                    //arr.push("进行中");
                }
                return arr.join(" ");
            }

        }, {
            field: 'progressTime',
            title: '进度时间',
            align: 'center',
            //visible: false,

        }, {
            field: 'progressTitle',
            title: '进度提示',
            align: 'center',
            visible: false,
        }, {
            field: 'delayOption',
            title: '延时审批',
            align: 'center',
            events: {
                'click .glyphicon-edit': function (e, value, row, index) {
                    var obj = { state: 2 };

                    //询问框
                    parent.layer.confirm('请确认，是否同意当前进度需要延时！', {
                        btn: ['确定', '取消'], //按钮
                        shade: false //不显示遮罩
                    }, function (index, layero) {

                        parent.layer.close(index);

                        //进行ajax传值
                        $.ajax({
                            url: "/BusinessLoan/EditAsync4ExpTime",
                            type: "post",
                            dataType: "json",
                            data: { id: value, curIdx: -1, str: JSON.stringify(obj) },
                            success: function (data) {
                                //Info,Success,Warning,Error
                                var type = data.type;
                                //console.log(Number(svcIdx) + 1); console.log(data);
                                if (type == 1) {

                                    layer.msg(data.content, { icon: 6, time: 2000 },
                                        function () {
                                            var index = parent.layer.getFrameIndex(window.name);
                                            parent.layer.close(index);

                                            $table.bootstrapTable('refresh');
                                        });

                                } else {
                                    layer.msg(data.content, { icon: 5, time: 2000 });
                                    window.location.reload();
                                }
                            }
                        });
                    });
                }
            },
            formatter: function (value, row, index) {
                var _arr = ['<i class="glyphicon glyphicon-edit pull-right" aria-hidden="true" title="审批"></i>']
                if (value == "0" || !isAuthority('314')) {
                    _arr = [""];
                }
                return _arr.join("", _arr);
            }
        }, {
            field: 'remark',//报备备注
            title: '备注',
            align: 'center',
            events: {
                'click .glyphicon-edit': function (e, value, row, index) {
                    openEditRunning('修改金融流水信息', 1, row.id, index);
                }
            },
            formatter: function (value, row, index) {
                var _arr = [value];
                if (isAuthority('297')) {
                    _arr.push('<i class="glyphicon glyphicon-edit pull-right" aria-hidden="true" title="修改"></i>');
                }
                return _arr.join(" ", _arr);
            }

            //}, {
            //    title: '资料图片',
            //    align: 'center',
            //    //visible: false,
            //}, {

            //    field: 'collectDataRemark',//资料收集说明
            //    title: '修改资料',
            //    align: 'center',
            //    //visible: false,
            //}, {
            //    title: '佣金',
            //    align: 'center',
            //    //visible: false,
            //}, {
            //    title: '已结佣金',
            //    align: 'center',
            //    //visible: false,

            //}, {
            //    title: '未结佣金',
            //    align: 'center',
            //    //visible: false,
            //}, {
            //    title: '佣金状态',
            //    align: 'center',
            //    //visible: false,
            //}, {
            //    title: '审核',
            //    align: 'center',
            //    //visible: false,
            //}, {
            //    title: '结算',
            //    align: 'center',
            //    //visible: false,
            //}, {
            //    title: '费用',
            //    align: 'center',
            //    //visible: false,            
        }, {
            title: '操作',
            align: 'center',
            //events: {
            //    'click .edit': function (e, value, row, index) {
            //        console.log("....");
            //    },
            //    'click .remove': function (e, value, row, index) {

            //    }
            //},
            formatter: function (value, row, index) {
                var arr = ['<a class="edit" href="/Finance/BusinessLoan/Edit?id=' + row.id + '&name=' + row.financeItemsName + '" title="金融审核">',
                            '操作',
                            '</a>  '];
                return arr.join(" ");
            }
        }]
    });
}

function openEditRunning(win_name, type, id, idx) {
    //type =9修改客户姓名；=10电话
    parent.layer.open({
        type: 2,
        title: win_name,
        shadeClose: false,
        shade: 0.4,
        area: ['400px', '300px'],
        content: '/Finance/Running/Edit?id=' + id + '&type=' + type,
        end: function () {
            editCallback(id, idx);
            //refreshTable();
        }
    });
}

//查询的参数
var queryParams = function (params) {
    var temp = {
        pageSize: params.limit,                             //行数
        pageIndex: (params.offset / params.limit) + 1,      //页码
        //itemId: $.getUrlParam('id'),
        //searchKey: $('.searchKey').val(),                       //查询内容
        //searchLimit: $('#searchLimit').val(),
        beginDate: $('#beginDate').val(),
        endDate: $('#endDate').val(),
        keyLimit: $('#keyLimit').val(),
        searchLimit: $('#searchLimit').val(),
        runningState: $('#runningState').val(),
        progressState: $('#progressState').val(),
        progress: $('#progress').val(),
        searcgKey: $('#searcgKey').val(),
    };
    $('#pageSize').val(temp.pageSize);
    $('#pageIndex').val(temp.pageIndex);
    console.log(temp);
    return temp;
};


//自定义的列事件
function operateFormatter(value, row, index) {
    return [
        '<a class="edit" href="javascript:void(0)" title="上移">',
        ' <i class="glyphicon glyphicon-upload" aria-hidden="true"></i>',
        '</a>  ',
        '<a class="remove" href="javascript:void(0)" title="下移">',
        ' <i class="glyphicon glyphicon-download" aria-hidden="true"></i>',
        '</a>'
    ].join('');
}

window.operateEvents = {
    'click .edit': function (e, value, row, index) {
        console.log("up");
        moveTo2(row.id, 1);
    },
    'click .remove': function (e, value, row, index) {
        console.log("down");
        moveTo2(row.id, -1);
    }
};


function isTrueFormatter(value, row, index) {
    return value ? '<i class="glyphicon glyphicon-ok"></i>' : '<i class="glyphicon glyphicon-remove"></i>'
}

//刷新表格数据
var refreshTable = function () {
    $table.bootstrapTable('refresh');
}

//获取表格高度
function getHeight() {
    return $(window).height() - 150;
}

//重置表格高度
setTimeout(function () {
    $table.bootstrapTable('resetView');
}, 200);

//重置表格高度
$(window).resize(function () {
    $table.bootstrapTable('resetView', {
        height: getHeight()
    });
});

//刷新按钮
$('#refreshBtn').click(function (e) {
    $table.bootstrapTable('refresh');
});

//搜索按钮
$('#searchBtn').click(function (e) {
    $table.bootstrapTable('refresh');
});
$('#btn-search-all').click(function (e) {
    $table.bootstrapTable('refresh');
})

function get7DaysBefore(date) {
    var date = date || new Date(),
        timestamp, newDate;
    if (!(date instanceof Date)) {
        date = new Date(date.replace(/-/g, '/'));
    }
    timestamp = date.getTime();
    newDate = new Date(timestamp - 7 * 24 * 3600 * 1000);
    return [[newDate.getFullYear(), newDate.getMonth() + 1, newDate.getDate()].join('/'), [newDate.getHours(), newDate.getMinutes(), newDate.getSeconds()].join(':')].join(' ');
}


//插入按钮
$('#insertBtn').click(function (e) {
    parent.layer.open({
        type: 2,
        title: '添加金融项属性',
        shadeClose: false,
        shade: 0.4,
        area: ['600px', '540px'],
        content: '/Finance/ItemAttribute/Insert?id=' + $('#item_id').val(),//$.getUrlParam('id'),// 
        end: function () {
            refreshTable();
        }
    });
});

//编辑按钮
$('#editBtn').click(function (e) {
    var selected = $table.bootstrapTable('getSelections');

    if (selected.length > 1) {
        layer.msg("一次只能修改一条数据！", { icon: 5, time: 2000 });
        return;
    }

    if (selected.length == 0) {
        layer.msg("请选择您要修改的数据！", { icon: 5, time: 2000 });
        return;
    }
    //var allData = [];
    //$.each($table.bootstrapTable('getData'), function (i, val) {
    //    allData.push({ idx: i, data: val });
    //});
    //var ttids = $.Enumerable.From(allData)
    //    .Where(function (x) { return x.data.id == selected[0].id; })
    //    .Select(function (x) { return { idx: x.idx, id: x.data.id }; })
    //    .First();

    editData(selected[0].id);
});
function editCallback(id, idx) {
    //EditModel
    $.ajax({
        url: "/Finance/Running/EditModel",
        type: "post",
        dataType: "json",
        data: { id: id },
        success: function (data) {
            //Info,Success,Warning,Error
            var type = data.type;
            if (type == 1) {
                $table.bootstrapTable('updateRow', { index: idx, row: data.data });
            } else {
                layer.msg(data.content, { icon: 5, time: 2000 });
            }
        }
    });
}

////打开编辑窗口
//function editData(id, idx) {
//    parent.layer.open({
//        type: 2,
//        title: '修改考勤设置',
//        shadeClose: true,
//        shade: 0.4,
//        area: ['880px', '540px'],
//        content: '/Finance/ItemAttribute/Edit?id=' + id,
//        end: function () {
//            editCallback(id, idx);
//            //refreshTable();
//        }
//    });
//}

//删除按钮
$('#deleteBtn').click(function (e) {
    var selected = $table.bootstrapTable('getSelections');
    if (selected.length == 0) {
        layer.msg("请选择您要删除的数据！", { icon: 5, time: 2000 });
        return;
    }

    var arr = [];
    for (var i = 0; i < selected.length; i++) {
        arr.push(selected[i].id);
    }

    var ids = arr.join(",");


});